package com.test.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 题目：一个初始值为0 的变量，两个线程对其操作，一个+1 一个-1，来5轮
 * 高并发： 高内聚低耦合的前提下
 * 1.线程 操作(方法) 资源类，
 * 2.判断 干活 通知唤醒
 * 3.防止虚假唤醒机制
 */
public class ProdConsumer1 {
    public static void main(String[] args) {
        ShareData data = new ShareData();
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                data.increment();
            }
        },"AA").start();

        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                data.decrement();
            }
        },"BB").start();
    }
}

//资源类
class ShareData{

    private volatile int number = 0;
    private Lock lock = new ReentrantLock();
    private Condition producer_con = lock.newCondition();
    private Condition consumer_con = lock.newCondition();

    public void increment(){
        lock.lock();
        try {
            //1.判断
            while (number != 0){
                //等待，不能生产
                producer_con.await();
            }
            //2.干活
            number++;
            System.out.println(Thread.currentThread().getName()+"\t"+number);
            //3.通知唤醒
            consumer_con.signal();
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            lock.unlock();
        }
    }

    public void decrement(){
        lock.lock();
        try{
            //1.判断
            while (number == 0){
                //等待，不能消费
                consumer_con.await();
            }
            //2.干活
            number--;
            System.out.println(Thread.currentThread().getName()+"\t"+number);
            //3.通知唤醒
            producer_con.signal();
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

}